import { FileManageModel } from '@/network'
import { IEditData, IFileListM } from '@/typing'

const http = new FileManageModel()

// 接口
interface IPageConfig {
  total: number
  pageSize: number
  pageNo: number
}

interface IData {
  editDialogShow: boolean
  deleteDialogShow: boolean
  searchValue: string
  currentPageIndex: number
  fileList: IFileListM[]
  showList: IFileListM[]
  pageConfigTotal: IPageConfig
}

interface IUseFileList {
  getFileList: (data: IData) => void
  selectFile: (e: any, data: IData) => void
  reFreshList: (list: IFileListM[], data: IData) => void
  changePage: (i: number, data: IData) => void
  DConfirmTrue: (id: number, data: IData) => void
  editConfirmTrue: (editData: IEditData, data: IData) => void
}

//  方法
function useFileList(): IUseFileList {
  // 暂存查询后返回的数据
  let SCList: IFileListM[] = []

  async function getFileList(data: IData) {
    const res = await http.getFileList()
    reFreshList(res, data)
  }

  async function selectFile(e: any, data: IData) {
    const fd = new FormData()
    fd.append('file', e.target.files[0])
    await http.addFileData(fd)
    getFileList(data)
  }

  function changePage(i: number, data: IData) {
    data.pageConfigTotal.pageNo = i
    const size = data.pageConfigTotal.pageSize
    const start = size * (i - 1)
    const end = size * i
    if (data.searchValue.trim().length > 0) {
      data.showList = SCList.slice(start, end)
    } else {
      data.showList = data.fileList.slice(start, end)
    }
    data.currentPageIndex = start
  }

  function reFreshList(list: IFileListM[], data: IData) {
    data.searchValue.trim().length > 0 ? (SCList = list) : (data.fileList = list)
    data.pageConfigTotal.total = list.length
    changePage(1, data)
  }

  async function DConfirmTrue(id: number, data: IData) {
    await http.DFileData(id)
    getFileList(data)
    data.deleteDialogShow = false
  }

  async function editConfirmTrue(editData: IEditData, data: IData) {
    await http.EFileData(editData)
    data.editDialogShow = false
    getFileList(data)
  }
  return {
    // 获取文件数据列表
    getFileList,
    // 上传文件
    selectFile,
    // 赋值 fileList 和 赋值分页配置
    reFreshList,
    // 设置当前展示列表 showList
    changePage,
    // 修改按钮
    editConfirmTrue,
    // 删除按钮
    DConfirmTrue
  }
}

export { useFileList }
